<template>
  <a-drawer
    :body-style="{ paddingBottom: '80px' }"
    :closable="false"
    :title="submitFlag === 'save' ?'新增设备':'编辑设备'"
    :visible="visible"
    :width="500"
    @close="onClose"
  >
    <a-form :form="form" layout="vertical">
      <a-row :gutter="16">
        <a-col :span="12">
          <a-form-item style="display:none">
            <a-input v-decorator="['id']"/>
          </a-form-item>
          <a-form-item label="设备名称">
            <a-input v-decorator="['deviceName']" placeholder="请输入设备名称"/>
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="设备SN">
            <a-input v-decorator="['deviceNo', {rules: [{ required: true, message: '请输入设备SN', whitespace: true}]}]" placeholder="请输入设备SN"/>
          </a-form-item>
        </a-col>
      </a-row>
      <a-row :gutter="16">
        <a-col :span="12">
          <a-form-item label="通道号">
            <a-input v-decorator="['passNo']" placeholder="请输入通道号"/>
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="设备类型">
            <a-select placeholder="请选择设备类型" v-decorator="['deviceType']">
              <a-select-option v-for="(action) in dictDataDeviceType" :key="action.dictValue">
                {{ action.dictLabel }}
              </a-select-option>
            </a-select>
          </a-form-item>
        </a-col>
      </a-row>
      <a-row :gutter="16">
        <a-col :span="12">
          <a-form-item label="设备违法类型">
            <a-select placeholder="请选择设备违法类型" v-decorator="['deviceIllegalType']">
              <a-select-option v-for="(action) in dictDataIllegalType" :key="action.dictValue">
                {{ action.dictLabel }}
              </a-select-option>
            </a-select>
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item>
            <span slot="label">
              设备状态
              <a-tooltip placement="topLeft" title="启用/禁用设备">
                <a-icon type="question-circle" theme="twoTone"/>
              </a-tooltip>
            </span>
            <a-radio-group
              v-decorator="['status', {initialValue: '1'}]">
              <a-radio value="1">
                启用
              </a-radio>
              <a-radio value="0">
                禁用
              </a-radio>
            </a-radio-group>
          </a-form-item>
        </a-col>
      </a-row>
      <a-row :gutter="16">
        <a-col :span="12">
          <a-form-item>
            <span slot="label">
              监控点编号
              <a-tooltip placement="topLeft" title="注意:监控点编号须与【海康ISC平台】保持一致海康ISC平台监控点编号查找路径：系统管理 ->设备管理 ->视频 ->编码设备详情 -> 监控点 ->点击编辑 -> 页面显示的“监控点编号”例如:c218924184d047c697c06321ed9afa7b">
                <a-icon type="question-circle" theme="twoTone"/>
              </a-tooltip>
            </span>
            <a-input v-decorator="['monitorNo']" placeholder="请输入监控点编号"/>
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="公安备案号">
            <a-input v-decorator="['keepDeviceNo', {rules: [{ required: true, message: '请输入公安备案号', whitespace: true}]}]" placeholder="请输入公安备案号"/>
          </a-form-item>
        </a-col>
      </a-row>
      <a-row :gutter="16">
        <a-col :span="24">
          <a-form-item label="道路名称">
            <a-select placeholder="请选择道路名称" v-decorator="['roadId', {rules: [{ required: true, message: '请选择道路名称', whitespace: true}]}]">
              <a-select-option v-for="(action) in roadNames" :key="action.id">
                {{ action.roadName }}
              </a-select-option>
            </a-select>
          </a-form-item>
        </a-col>
      </a-row>
      <a-row :gutter="16">
        <a-col :span="24">
          <a-form-item label="设备禁停标示图片">
            <a-upload
              name="avatar"
              list-type="picture-card"
              class="avatar-uploader"
              :show-upload-list="false"
              :customRequest="uploadMethod"
              :before-upload="beforeUpload"
              @change="handleChange"
            >
              <img v-if="forbidImage" :src="forbidImage" alt="avatar" style="width: 120px;" />
              <div v-else>
                <a-icon :type="loading ? 'loading' : 'plus'" />
                <div class="ant-upload-text">
                  上传图片
                </div>
              </div>
            </a-upload>
            <a-button v-show="this.showImageView" @click="handlePreview">查看图片</a-button>
          </a-form-item>
        </a-col>
      </a-row>
    </a-form>
    <div
      :style="{
        position: 'absolute',
        right: 0,
        bottom: 0,
        width: '100%',
        borderTop: '1px solid #e9e9e9',
        padding: '10px 16px',
        background: '#fff',
        textAlign: 'right',
        zIndex: 1,
      }"
    >
      <a-popconfirm title="真的放弃编辑吗?" @confirm="onClose">
        <a-button :style="{ marginRight: '8px' }">
          取消
        </a-button>
      </a-popconfirm>
      <a-button type="primary" @click="handleSubmit">
        保存
      </a-button>
    </div>
    <a-modal :visible="previewVisible" :footer="null" @cancel="handleCancel">
      <img alt="example" style="width: 100%" :src="forbidImage" />
    </a-modal>
  </a-drawer>
</template>

<script>
import pick from 'lodash.pick'
import { addDevice, dictDataList, editDevice, findAllRoadList, uploadForbidImage } from '@/api/system'
export default {
  name: 'PlateSettingModal',
  data () {
    return {
      dictDataDeviceType: [],
      dictDataIllegalType: [],
      roadNames: [],
      form: this.$form.createForm(this),
      visible: false,
      mdl: {},
      disabled: false,
      title: '添加字典数据',
      submitFlag: null,
      previewVisible: false,
      loading: false,
      forbidImage: '',
      showImageView: false,
      imageUrlPrefix: process.env.VUE_APP_IMAGE_URL_PREFIX
    }
  },
  created () {
    this.loadDictDataDeviceType()
    this.loadDictDataIllegalType()
    this.loadAllRoad()
  },
  methods: {
    handlePreview () {
      this.previewVisible = true
    },
    handleCancel () {
      this.previewVisible = false
    },
    uploadMethod: function ({ onProgress, onError, filename, file }) {
      return new Promise(async () => {
        const formObj = new FormData()
        formObj.append('file', file)
        formObj.append('deviceNo', this.form.getFieldValue('deviceNo'))
        formObj.append('passNo', this.form.getFieldValue('passNo'))
        try {
          const res = await uploadForbidImage(formObj)
          // 成功之后赋值
          this.forbidImage = this.imageUrlPrefix + `${res.data}?v=${Date.now()}`
          this.showImageView = true
        } catch (error) {
          this.$message.error('上传失败!')
        }
      })
    },
    handleChange (info) {
      if (info.file.status === 'uploading') {
        this.loading = true
      }
    },
    beforeUpload (file) {
      const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png'
      if (!isJpgOrPng) {
        this.$message.error('只能上传JPG或者PNG文件!')
      }
      const isLt10M = file.size / 1024 / 1024 < 10
      if (!isLt10M) {
        this.$message.error('图片必须小于10MB!')
      }
      const deviceIsNull = !this.form.getFieldValue('deviceNo')
      const passNoIsNull = !this.form.getFieldValue('passNo')
      if (!this.form.getFieldValue('deviceNo') && !this.form.getFieldValue('passNo')) {
        this.$message.error('上传禁停标识图片前请先确定，设备SN和通道号是否填写')
      }
      return isJpgOrPng && isLt10M && !deviceIsNull && !passNoIsNull
    },
    loadDictDataDeviceType () {
      dictDataList({ dictType: 'device_type' }).then(res => {
        this.dictDataDeviceType = res.data
      })
    },
    loadDictDataIllegalType () {
      dictDataList({ dictType: 'illegal_type' }).then(res => {
        this.dictDataIllegalType = res.data
      })
    },
    loadAllRoad () {
      findAllRoadList().then(res => {
        this.roadNames = res.data
      })
    },
    add () {
      this.submitFlag = 'save'
      this.form.resetFields()
      this.visible = true
    },
    edit (record) {
      this.submitFlag = 'edit'
      this.mdl = Object.assign({}, record)
      this.visible = true
      if (record.forbidImage) {
        this.forbidImage = null
        this.showImageView = true
        this.forbidImage = this.imageUrlPrefix + record.forbidImage
      }
      this.$nextTick(() => {
        this.form.setFieldsValue(pick(this.mdl, 'id', 'deviceName', 'deviceNo', 'passNo', 'deviceType', 'deviceIllegalType', 'status', 'monitorNo', 'keepDeviceNo', 'roadId'))
      })
    },
    onClose () {
      this.visible = false
      this.forbidImage = null
      this.showImageView = false
    },
    handleSubmit (e) {
      e.preventDefault()
      this.form.validateFields((err, values) => {
        const url = this.forbidImage.split('?')[0]
        values.forbidImage = url.split('/path/')[1]
        if (!err) {
          if (this.submitFlag === 'save') {
            addDevice(values).then(res => {
              if (res.code === 200) {
                this.$message.success('操作成功')
                this.$emit('ok')
                this.visible = false
              }
            }).catch(res => {
              this.$message.error(((res.response || {}).data || {}).message || res.message)
            })
          } else {
            editDevice(values).then(res => {
              if (res.code === 200) {
                this.$message.success('操作成功')
                this.$emit('ok')
                this.visible = false
              }
            }).catch(res => {
              this.$message.error(((res.response || {}).data || {}).message || res.message)
            })
          }
        }
      })
    }
  }
}
</script>

<style scoped>
.avatar-uploader > .ant-upload {
  width: 128px;
  height: 128px;
}
.ant-upload-select-picture-card i {
  font-size: 32px;
  color: #999;
}

.ant-upload-select-picture-card .ant-upload-text {
  margin-top: 8px;
  color: #666;
}
</style>
